package com.hs.framework.view

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import androidx.annotation.Nullable
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hs.framework.base.BaseRecyclerAdapter
import com.hs.framework.databinding.ViewPaginationrecyclerBinding

/**
 * 分页的RecyclerView
 */
class PaginationRecyclerView : LinearLayout{

    private  var  mbinding : ViewPaginationrecyclerBinding? = null
    private var adapter : BaseRecyclerAdapter<*>? = null
    private var recyclerView :RecyclerView? = null
    private var mPaginationView : PaginationView? = null
    private var total = 0
    constructor(context: Context) : super(context) {
        init(context, null)
    }

    constructor(context: Context, @Nullable attrs: AttributeSet?) : super(context, attrs) {
        init(context, attrs)
    }

    constructor(context: Context, @Nullable attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        init(context, attrs)
    }

    private fun init(context: Context, @Nullable attrs: AttributeSet?) {
        mbinding = ViewPaginationrecyclerBinding.inflate(LayoutInflater.from(context),this,true)
        recyclerView = mbinding?.mRecyclerView
        recyclerView?.layoutManager = LinearLayoutManager(context)
//        adapter = PaginationRecyclerAdapter()
        mPaginationView = mbinding?.mPaginationView
        initListener()
    }

    private fun initListener() {
        mPaginationView?.setPaginationViewChangeCallback(object :PaginationView.PaginationViewChangeCallback{
            override fun onChange(index: Int) {
                // 刷新数据
                println("刷新数据:${index}")
                callback?.refreshData(index)
            }
        })
    }


    // 设置Adapter的方法，接收BaseRecyclerAdapter的子类
    fun setAdapter(adapter: BaseRecyclerAdapter<*>) {
        this.adapter = adapter
        recyclerView?.adapter = adapter
    }

    fun setTotal(total:Int){
        this.total = total
        mPaginationView?.setTotal(total)
    }

    private var callback: PaginationRecyclerViewCallback<*>? = null

    public fun setPaginationRecyclerViewCallback(callback: PaginationRecyclerViewCallback<*>){
        this.callback = callback
    }

    interface PaginationRecyclerViewCallback<T> {
        fun refreshData(index: Int)
        fun onClickItem(item:T)
    }

    public fun destroyView(){
        mbinding?.mPaginationView?.destroyView()
        mbinding = null
    }


}